package com.handy.afdian.http;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.handy.afdian.param.AfDianRequest;
import com.handy.afdian.param.AfDianResponse;

import java.util.Map;

/**
 * 爱发电请求
 *
 * @author handy
 */
public class AfDian {

    private final static String PING_URL = "https://afdian.net/api/open/ping";
    private final static String QUERY_ORDER_URL = "https://afdian.net/api/open/query-order";
    private final static String QUERY_SPONSOR_URL = "https://afdian.net/api/open/query-sponsor";

    private final String userId;
    private final String token;

    public AfDian(String userId, String token) {
        this.userId = userId;
        this.token = token;
    }

    /**
     * ping
     *
     * @param params 参数
     */
    public AfDianResponse ping(Map<String, Object> params) {
        return sendPost(PING_URL, params);
    }

    /**
     * 查订单
     *
     * @param params 参数
     */
    public AfDianResponse queryOrder(Map<String, Object> params) {
        return sendPost(QUERY_ORDER_URL, params);
    }

    /**
     * 查赞助者
     *
     * @param params 参数
     */
    public AfDianResponse querySponsor(Map<String, Object> params) {
        return sendPost(QUERY_SPONSOR_URL, params);
    }

    /**
     * 发送请求
     *
     * @param url    url
     * @param params 参数
     * @return AfDianParam
     */
    private AfDianResponse sendPost(String url, Map<String, Object> params) {
        long ts = System.currentTimeMillis() / 1000;
        String paramsJson = JSONUtil.toJsonStr(params);
        String sign = token + "params" + paramsJson + "ts" + ts + "user_id" + userId;
        AfDianRequest afDianRequest = new AfDianRequest();
        afDianRequest.setUser_id(userId);
        afDianRequest.setParams(paramsJson);
        afDianRequest.setTs(ts);
        afDianRequest.setSign(SecureUtil.md5(sign));
        String responseJson = HttpUtil.post(url, JSONUtil.toJsonStr(afDianRequest));
        return JSONUtil.toBean(responseJson, AfDianResponse.class);
    }

}